<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="" method="" id="form">
        <input type="text" name="name" >
        <input type="text" name="age" >
        <input type="text" name="sex" >
        <button id="btn">点击有惊喜</button>
    </form>

    <script>
        //获取元素
        const oForm = document.getElementById('form');
        const oBtn = document.getElementById('btn');
        const oIpn = document.querySelector('#form input[name=name]')
        const oAge = document.querySelector('#form input[name=age]')
        const oSex = document.querySelector('#form input[name=sex]')
        //给表单添加事件
        oForm.onsubmit = function(){

            //获取input输入的值
            const nameValue = oIpn.value;
            const ageValue = oAge.value;
            const sexValue = oSex.value;
            //实例化
            const xhr = new XMLHttpRequest();
            //打开路径
            xhr.open('POST','postAll',true);
            //发送的类型
            xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
            //发送
            xhr.send(JSON.stringify({
                name : nameValue,
                age : ageValue,
                sex : sexValue 
            }))
            //绑定事件
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status <= 299)){
                    const data = JSON.parse(xhr.responseText);
                    console.log(data);
                }
            }
            return false
        }
    </script>

</body>
</html>